<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.deviceNo" placeholder="车载设备标识号" style="width: 150px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.deviceId" placeholder="车载设备实体号" style="width: 150px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.manufactor" placeholder="车载设备厂家" :loading="loadingOptions" clearable style="width: 150px" class="filter-item">
        <el-option v-for="item in deviceManufactorOptions" :key="item.label" :label="item.label" :value="item.label" />
      </el-select>
      <el-select v-model="listQuery.model" placeholder="车载设备型号" :loading="loadingOptions" clearable style="width: 150px" class="filter-item">
        <el-option v-for="item in deviceModelOptions" :key="item.label" :label="item.label" :value="item.label" />
      </el-select>

      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('table.search') }}
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="success" icon="el-icon-edit" @click="handleCreate">
        {{ $t('table.add') }}
      </el-button>
    </div>

    <div class="block block-custom">
      <el-table :key="tableKey" v-loading="listLoading" :data="list" highlight-current-row style="width: 100%;" @sort-change="sortChange" height="calc(85vh - 155px)">
        <el-table-column label="车载设备ID" prop="id" sortable align="center" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.deviceId }}</span>
          </template>
        </el-table-column>
        <el-table-column label="车载设备名称" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.deviceName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="车载设备标识号" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.deviceNo }}</span>
          </template>
        </el-table-column>
        <el-table-column label="车载设备厂家" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.manufactor }}</span>
          </template>
        </el-table-column>
        <el-table-column label="车载设备型号" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.model }}</span>
          </template>
        </el-table-column>
        <el-table-column label="车载设备出厂编号" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.factoryNo }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" label="车载设备状态">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.isActive === 0" type="danger" disable-transitions>未启用</el-tag>
            <el-tag v-if="scope.row.isActive === 1" type="success" disable-transitions>启用</el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" label="更改车载设备状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.isActive" active-color="#13ce66" inactive-color="#ff4949" :active-value="1"
              :inactive-value="0" @change="changeDeviceStatus(scope.row)"> </el-switch>
          </template>
        </el-table-column> -->

        <el-table-column :label="$t('table.actions')" align="center" width="230" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="primary" @click="handleUpdate(scope.row)">
              {{ $t('table.edit') }}
            </el-button>
            <el-button v-if="scope.row.status != 'deleted'" type="danger" @click="handleDeletedDevice(scope.row)">
              {{ $t('table.delete') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.size" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" class="view-dialog" :show-close="false" :modal="true">
      <el-form ref="dataForm" :model="deviceInfo" label-width="30%" style="width:70%;" :rules="rules">
        <el-form-item label="车载设备名称" prop="deviceName">
          <el-input v-model="deviceInfo.deviceName" />
        </el-form-item>
        <el-form-item label="车载设备标识号" prop="deviceNo">
          <el-input v-model="deviceInfo.deviceNo" />
        </el-form-item>
        <el-form-item label="车载设备类型" prop="deviceType">
          <el-input placeholder="车载设备" disabled />
        </el-form-item>
        <el-form-item label="车载设备厂家" prop="manufactor">
          <el-select v-model="deviceInfo.manufactor" placeholder="车载设备厂家" :loading="loadingOptions" clearable filterable allow-create class="filter-item">
            <el-option v-for="item in deviceManufactorOptions" :key="item.label" :label="item.label" :value="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="车载设备型号" prop="model">
          <el-select v-model="deviceInfo.model" placeholder="车载设备型号" :loading="loadingOptions" clearable filterable allow-create class="filter-item">
            <el-option v-for="item in deviceModelOptions" :key="item.label" :label="item.label" :value="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="车载设备出厂编号" prop="factoryNo">
          <el-input v-model="deviceInfo.factoryNo" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click.native="dialogStatus === 'create' ? createData() : updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDevicePageInfos, updateIsActive, getOptionList, deleteDevice, createOrUpdate } from '@/api/device'

import waves from '@/directive/waves' // Waves directive
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { setOrgOptions } from '../../memberOrgs'
import { updateMemberOrgs } from '@/api/organization'
import { getStationNames, addOrUpdateMemberStations, getJobTypeNames, getTaskTypeNames } from '@/api/station'
import { getRoles, getRoleOptions } from '@/api/role'

export default {
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      taskTypeNames: [],
      JobTypeNames: [],
      roleOptions: [],
      stationNames: [],
      isStationChanged: false,
      isOrgChanged: false,
      orgProps: {
        value: 'orgId', //匹配响应数据中的id
        label: 'orgName', //匹配响应数据中的name
        children: 'children', //匹配响应数据中的children
        checkStrictly: true
      },
      orgOptions: [],
      memberOrgForm: {
        memberId: 0,
        orgId: 0,
        memberType: 2
      },
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: false,
      loadingOptions: false,
      listQuery: {
        page: 1,
        size: 10,
        deviceNo: '',
        deviceType: 1,
        deviceId: '',
        manufactor: '',
        model: '',
        isActive: ''
      },
      deviceManufactorOptions: [],
      deviceModelOptions: [],
      deviceInfo: {
        deviceName: '',
        deviceNo: '',
        deviceType: 1,
        deviceId: '',
        manufactor: '',
        model: '',
        factoryNo: '',
        org: [],
        stationIds: [],
        roleId: null,
        jobTypeId: null,
        taskTypeIds: []
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑修改车载设备信息',
        create: '新增车载设备'
      },
      userInfoData: [],
      rules: {
        deviceNo: [{ required: true, message: '车载设备标识号不可空缺', trigger: 'blur' }],
        org: [{ required: true, message: '车载设备所属组织不可空缺', trigger: 'blur' }],
        // roleId: [{ required: true, message: '车载设备角色不可空缺', trigger: 'blur' }],
        // stationIds: [{ required: true, message: '车载设备所属车站不可空缺', trigger: 'blur' }],
        // jobTypeId: [{ required: true, message: '车载设备所属工种不可空缺', trigger: 'blur' }],
        // taskTypeIds: [{ required: true, message: '车载设备所属任务类型不可空缺', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
    setOrgOptions().then(res => {
      this.orgOptions.push(res)
    })
    this.getRoleOptions()
    this.getStationNameList()
    this.getJobTypeNameList()
    this.getTaskTypeNameList()
  },
  methods: {
    getTaskTypeNameList() {
      getTaskTypeNames().then(res => {
        this.taskTypeNames = res.data
      })
    },
    getJobTypeNameList() {
      getJobTypeNames().then(res => {
        this.JobTypeNames = res.data
      })
    },
    getRoleOptions: function() {
      getRoleOptions().then(res => {
        this.roleOptions = res.data
        this.deviceInfo.roleId = this.roleOptions[0].roleId
      })
    },
    stationChanged() {
      this.isStationChanged = true
    },
    getStationNameList() {
      getStationNames().then(res => {
        var objArray = res.data
        if (this.$store.getters.roles != 1) {
          this.stationNames = objArray
        } else {
          var numberArray = this.$store.getters.stationIds
          if (numberArray.length != 0) {
            for (var i = 0; i < objArray.length; i++) {
              var obj = objArray[i]
              // 判断当前对象的 stationNum 是否在数组 numberArray 中
              if (numberArray.indexOf(obj.stationNum) == -1) {
                // 将匹配的对象添加到新数组中
                obj.disabled = true
              }
            }
          }
          this.stationNames = objArray
        }
      })
    },
    orgChanged() {
      if (this.deviceInfo.org != []) {
        this.isOrgChanged = true
      }
    },
    //
    getList() {
      this.listLoading = true
      getDevicePageInfos(this.listQuery).then(response => {
        if (response.code === 0) {
          this.list = response.data.items
          this.total = response.data.total
          this.getDeviceNetStatus()
          this.listLoading = false
          this.getOptions()
        } else {
          this.$message.error(response.msg)
        }
      })
    },
    getDeviceNetStatus() {
      for (let i = 0; i < this.list.length; i++) {
        var netInfo = [{ netId: i, netStatus: 0 }, { netId: i + 1, netStatus: 1 }]
        this.list[i].netInfo = netInfo
      }
    },
    getOptions() {
      this.loadingOptions = true
      const manufactorOption = 1
      const modelOption = 2
      const deviceType = 1
      getOptionList(manufactorOption, deviceType).then(res => {
        this.deviceManufactorOptions = res.data.list
      })
      getOptionList(modelOption, deviceType).then(res => {
        this.deviceModelOptions = res.data.list
      })
      this.loadingOptions = false
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    calcPage() {
      let newPageing = Math.ceil((this.total - 1) / this.listQuery.size) //Math.ceil向上取整算出新的分页
      let currentPage = this.listQuery.page > newPageing ? newPageing : this.listQuery.page //计算当前页应该是哪页
      this.listQuery.page = currentPage < 1 ? 1 : currentPage //把当前页的值赋给this.page,重新渲染列表
    },
    handleDeletedDevice(row) {
      this.$confirm('此操作将永久删除该条目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteDevice(row.deviceId).then(res => {
            if (res.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success'
              })
              this.calcPage()
              this.getList()
            } else {
              this.$message({
                message: res.msg,
                type: 'error'
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.deviceInfo = {
        deviceName: '',
        deviceNo: '',
        deviceType: 1,
        deviceId: '',
        manufactor: '',
        model: '',
        factoryNo: '',
        org: [],
        stationIds: []
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.deviceInfo.roleId = this.roleOptions[0].roleId
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.SubmitFormData(this.deviceInfo)
        }
      })
    },
    SubmitFormData(formData) {
      createOrUpdate(formData).then(res => {
        if (res.data) {
          this.deviceInfo.deviceId = res.data.deviceId
          if (this.isStationChanged) {
            let data = {
              stationIds: this.deviceInfo.stationIds,
              memberId: this.deviceInfo.deviceId,
              memberType: 2
            }
            addOrUpdateMemberStations(data).then(res => {
              if (res.code != 0) {
                this.$message.error(res.msg)
              }
            })
          }
          if (this.isOrgChanged) {
            this.memberOrgForm.memberId = this.deviceInfo.deviceId
            this.memberOrgForm.memberType = 2
            this.memberOrgForm.orgId = this.deviceInfo.org.slice(-1)[0]
            updateMemberOrgs(this.memberOrgForm).then(res => {
              if (res.code == 0) {
                this.$message.success('车载设备信息提交成功')
              } else {
                this.$message.error(res.msg)
              }
              this.getList()
              this.dialogFormVisible = false
              this.isOrgChanged = false
            })
          } else {
            this.$message.success('车载设备信息提交成功')
            this.getList()
            this.dialogFormVisible = false
          }
        }
      })
    },
    handleUpdate(row) {
      Object.keys(this.deviceInfo).forEach(key => {
        if(row.hasOwnProperty(key))
        {
          this.deviceInfo[key] = row[key]
        }
        if (row.hasOwnProperty("jobType") && row.jobType != null) {
          this.deviceInfo.jobTypeId = row.jobType.jobTypeId
        }
      })
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.SubmitFormData(this.deviceInfo)
        }
      })
    },
    changeDeviceStatus(row) {
      updateIsActive(row.deviceId, row.isActive).then(res => {
        if (res.code === 0) {
          this.getList()
        } else {
          if (row.isActive === 1) {
            row.isActive = 0
          }
          if (row.isActive === 0) {
            row.isActive = 1
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.my-label {
  background: #8dca6f;
}

.block .el-range-separator {
  width: 24px;
}

/deep/ .el-table__body-wrapper::-webkit-scrollbar {
  width: 8px;
  /*滚动条宽度*/
  height: 8px;
  /*滚动条高度*/
}

/deep/ .el-table__body-wrapper::-webkit-scrollbar-track {
  border-radius: 0px;
  /*滚动条的背景区域的圆角*/
  background-color: rgba(2, 29, 87, 1);
  /*滚动条的背景颜色*/
}

/deep/ .el-table__body-wrapper::-webkit-scrollbar-corner {
  background-color: rgba(2, 29, 87, 1);
}

/deep/ .el-table__body-wrapper::-webkit-scrollbar-thumb {
  border-radius: 4px;
  /*滚动条的圆角*/
  background-color: rgba(24, 144, 255, 0.5);
  /*滚动条的背景颜色*/
}

/* 弹窗 */
/* 改变高度弹窗位置*/
/deep/ .dialog-content .el-dialog__body {
  height: 40vh;
  overflow: auto;
}

/deep/ .view-dialog > .el-dialog {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 2px 2px 5px #d0d0d0;
}

/deep/ .view-dialog > .el-dialog > .el-dialog__header {
  width: 100%;
  height: 54px;
  line-height: 54px;
  text-align: center;
  background: #f4f5f7;
  border-radius: 12px 12px 0px 0px;
  font-size: 20px;
  font-family: Source Han Sans CN;
  font-weight: 400;
  color: #252b3a;
  padding: 0 0 0 40px;
  padding-left: 0;
}

/deep/ .view-dialog > .el-dialog > .el-dialog__footer {
  padding-left: 0;
  padding-right: 0;
  text-align: center;
}

/deep/ .dialog-form > .el-form-item {
  margin-bottom: 30px;
}

/deep/ .dialog-form > .el-form-item > .el-form-item__content > .el-input > .el-input__inner {
  width: 220px;
  height: 34px;
  background: #ffffff;
  border: 1px solid #dcdee2;
  border-radius: 3px;
}

/deep/ .dialog-form > .el-form-item > .el-form-item__content > .el-select > .el-input > .el-input__inner {
  width: 220px;
  height: 34px;
  background: #ffffff;
  border: 1px solid #dcdee2;
  border-radius: 3px;
}

/deep/ .view-dialog > .el-dialog > .el-dialog__header > .el-dialog__headerbtn {
  top: 0;
}

/deep/ .view-dialog .el-form-item__content {
  width: 100%;
}
</style>
